'use client';
import { useState, useEffect, useCallback } from 'react';
import { useSession } from 'next-auth/react';
import PromptList from '@/components/prompt/PromptList';
import { Input } from "@/components/ui/input"
import { Spinner } from '@/components/ui/Spinner';
import TagFilter from '@/components/prompt/TagFilter';
import { Button } from "@/components/ui/button"
import { Search, PlusCircle, ChevronDown, Copy, Share2, Trash2, Clock, Tags, Wand2, Loader2, HelpCircle } from "lucide-react"
import { Skeleton } from "@/components/ui/skeleton"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { useToast } from "@/hooks/use-toast"
import { Card } from "@/components/ui/card"
import Image from 'next/image';
import Link from 'next/link';
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import dynamic from 'next/dynamic'
import { useLanguage } from '@/contexts/LanguageContext';
import * as VisuallyHidden from '@radix-ui/react-visually-hidden';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"

const CreatableSelect = dynamic(() => import('react-select/creatable'), {
  ssr: false
});

// Custom debounce function
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

const PromptCardSkeleton = () => {
  return (
    <Card className="group relative p-5 hover:shadow-md transition-all bg-card border border-border/40">
      <div className="space-y-4">
        <div className="flex justify-between items-start">
          <div className="space-y-2">
            <Skeleton className="h-6 w-[180px]" />
            <Skeleton className="h-4 w-[240px]" />
          </div>
          <Skeleton className="h-8 w-24 rounded-lg" />
        </div>

        <div className="flex flex-wrap gap-2">
          <Skeleton className="h-5 w-16 rounded-full" />
          <Skeleton className="h-5 w-20 rounded-full" />
          <Skeleton className="h-5 w-14 rounded-full" />
        </div>

        <div className="flex items-center gap-2">
          <Skeleton className="h-4 w-4" />
          <Skeleton className="h-4 w-32" />
        </div>
      </div>
    </Card>
  );
};

const PromptListSkeleton = () => {
  return (
    <div className="mt-8 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
      <Card className="group relative border p-5 hover:shadow-md transition-all bg-card cursor-pointer border-dashed h-[180px] flex items-center justify-center">
        <div className="flex flex-col items-center gap-2">
          <Skeleton className="h-10 w-10 rounded-full" />
          <Skeleton className="h-5 w-24" />
        </div>
      </Card>
      {[...Array(5)].map((_, index) => (
        <PromptCardSkeleton key={index} />
      ))}
    </div>
  );
};

async function getPrompts() {
  const res = await fetch('/api/prompts',{
    method:'GET',
    headers: {
      'Content-Type': 'application/json',
    },
  });
  if (!res.ok) {
    throw new Error('Failed to fetch prompts');
  }
  return res.json();
}

async function deletePrompt(id) {
  const res = await fetch(`/api/prompts/${id}`, {
    method: 'DELETE',
    headers: {
      'Content-Type': 'application/json',
    },
  });
  if (!res.ok) {
    throw new Error('Failed to delete prompt');
  }
  return res.json();
}

// Modified NewPromptCard with enhanced styling
const NewPromptCard = ({ onClick }) => {
  const { t } = useLanguage();
  if (!t) return null;
  return (
    <Card 
      onClick={onClick}
      className="group relative border p-5 hover:shadow-xl transition-all duration-300 ease-in-out bg-card cursor-pointer border-dashed h-[180px] flex items-center justify-center overflow-hidden"
    >
      <div className="flex flex-col items-center gap-3 text-muted-foreground group-hover:scale-110 transition-transform duration-300">
        <div className="bg-primary/10 p-3 rounded-full">
          <PlusCircle className="h-8 w-8 text-primary" />
        </div>
        <span className="text-sm font-medium">{t.promptsPage.newPromptCard}</span>
      </div>
      <div className="absolute inset-0 bg-gradient-to-br from-primary/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
    </Card>
  );
};

export default function PromptsPage() {
  const { language, t } = useLanguage();
  const { toast } = useToast();
  const { data: session } = useSession();
  const [prompts, setPrompts] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedTags, setSelectedTags] = useState([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [promptToDelete, setPromptToDelete] = useState(null);
  const [selectedVersions, setSelectedVersions] = useState(null);
  const [showNewPromptDialog, setShowNewPromptDialog] = useState(false);
  const [showOptimizeModal, setShowOptimizeModal] = useState(false);
  const [optimizedContent, setOptimizedContent] = useState('');
  const [isOptimizing, setIsOptimizing] = useState(false);
  const [newPrompt, setNewPrompt] = useState({
    title: '',
    content: '',
    description: '',
    tags: 'Agent', 
    version: '1.0.0',
    cover_img: '',
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [tagOptions, setTagOptions] = useState([]);
  const [showModelConfig, setShowModelConfig] = useState(false);
  const [modelConfig, setModelConfig] = useState({
    channel: '',
    channel_id: null,
    model: '',
    temperature: 1.0,
    max_tokens: 2048,
    top_p: 1.0,
    presence_penalty: 0.0,
    frequency_penalty: 0.0,
    n: 1,
    stop: '',
    logit_bias: '',
    stream: true,
    api_key: ''
  });

  const [channels, setChannels] = useState([]);
  const [models, setModels] = useState([]);

  const validateModelConfig = () => {
    if (!modelConfig.channel || modelConfig.channel.trim() === '') {
      toast({ variant: 'destructive', description: '渠道名称不能为空' });
      return false;
    }
    if (!modelConfig.model || modelConfig.model.trim() === '') {
      toast({ variant: 'destructive', description: '模型名称不能为空' });
      return false;
    }
    const temperature = Number(modelConfig.temperature);
    if (Number.isNaN(temperature) || temperature < 0 || temperature > 2) {
      toast({ variant: 'destructive', description: 'temperature 取值范围应在 [0, 2]' });
      return false;
    }
    const top_p = Number(modelConfig.top_p);
    if (Number.isNaN(top_p) || top_p < 0 || top_p > 2) {
      toast({ variant: 'destructive', description: 'top_p 取值范围应在 [0, 2]' });
      return false;
    }
    const max_tokens = Number(modelConfig.max_tokens);
    if (Number.isNaN(max_tokens) || max_tokens < 10 || max_tokens > 30000) {
      toast({ variant: 'destructive', description: 'max_tokens 取值范围应在 [10, 30000]' });
      return false;
    }
    const presence_penalty = Number(modelConfig.presence_penalty);
    if (Number.isNaN(presence_penalty) || presence_penalty < -2 || presence_penalty > 2) {
      toast({ variant: 'destructive', description: 'presence_penalty 取值范围应在 [-2.0, 2.0]' });
      return false;
    }
    const frequency_penalty = Number(modelConfig.frequency_penalty);
    if (Number.isNaN(frequency_penalty) || frequency_penalty < -2 || frequency_penalty > 2) {
      toast({ variant: 'destructive', description: 'frequency_penalty 取值范围应在 [-2.0, 2.0]' });
      return false;
    }
    return true;
  };

  const debouncedSearch = useCallback((value) => {
    const timeoutId = setTimeout(() => {
      setSearchQuery(value);
    }, 300);
    return () => clearTimeout(timeoutId);
  }, []);

  useEffect(() => {
    const fetchPrompts = async () => {
      try {
        setIsLoading(true);
        const data = await getPrompts();
        setPrompts(data.map(prompt => ({
          ...prompt,
          version: prompt.version || '1.0',
          cover_img: prompt.cover_img || '/default-cover.jpg',
          tags: prompt.tags?.split(',') || []
        })));
      } catch (error) {
        console.error('Error fetching prompts:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchPrompts();
  }, []);

  useEffect(() => {
    const fetchTags = async () => {
      try {
        const response = await fetch('/api/tags');
        const data = await response.json();
        const mappedTags = data.map(tag => ({ 
          value: tag.name, 
          label: tag.name 
        }));
        setTagOptions(mappedTags);
      } catch (error) {
        console.error('Error fetching tags:', error);
      }
    };

    fetchTags();
  }, []);

  useEffect(() => {
    const fetchChannels = async () => {
      if (!session?.user?.accessToken) return;
      
      try {
        const response = await fetch(`/api/models/channels`, {
          headers: {
            'Authorization': `Bearer ${session.user.accessToken}`
          }
        });
        const data = await response.json();
        if (data.code === 200 && data.data) {
          setChannels(data.data);
        }
      } catch (error) {
        console.error('Error fetching channels:', error);
      }
    };

    fetchChannels();
  }, [session?.user?.accessToken]);

  // 当渠道改变时，获取对应的模型列表
  useEffect(() => {
    const fetchModels = async () => {
      if (!modelConfig.channel_id || !session?.user?.accessToken) {
        setModels([]);
        return;
      }

      try {
        const response = await fetch(`/api/models/models/${modelConfig.channel_id}`, {
          headers: {
            'Authorization': `Bearer ${session.user.accessToken}`
          }
        });
        const data = await response.json();
        if (data.code === 200 && data.data) {
          setModels(data.data);
        }
      } catch (error) {
        console.error('Error fetching models:', error);
      }
    };

    fetchModels();
  }, [modelConfig.channel_id, session?.user?.accessToken]);

  if (!t) return null;
  const tp = t.promptsPage;

  const handleCopy = async (content) => {
    try {
      await navigator.clipboard.writeText(content);
      toast({
        description: tp.copySuccess,
        duration: 2000,
      });
    } catch (err) {
      console.error('Copy failed:', err);
      toast({
        variant: "destructive",
        description: tp.copyError,
        duration: 2000,
      });
    }
  };

  const handleDelete = async (id) => {
    setPromptToDelete(id);
    setDeleteDialogOpen(true);
  };

  const confirmDelete = async () => {
    try {
      await deletePrompt(promptToDelete);
      setPrompts(prompts.filter(prompt => prompt.id !== promptToDelete));
      setDeleteDialogOpen(false);
      toast({
        description: tp.deleteSuccess,
        duration: 2000,
      });
    } catch (error) {
      console.error('Error deleting prompt:', error);
      toast({
        variant: "destructive",
        description: tp.deleteError,
        duration: 2000,
      });
    }
  };

  const filteredPrompts = prompts.filter(prompt => {
    const matchesTags = selectedTags.length === 0 || 
      selectedTags.every(tag => prompt.tags.includes(tag));
    const matchesSearch = prompt.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      prompt.description.toLowerCase().includes(searchQuery.toLowerCase());
    return matchesTags && matchesSearch;
  });

  const allTags = [...new Set(prompts.flatMap(prompt => prompt.tags))];

  const handleShare = async (id) => {
    const shareUrl = `${window.location.origin}/share/${id}`;
    try {
      await navigator.clipboard.writeText(shareUrl);
      toast({
        description: tp.shareSuccess,
        duration: 2000,
      });
    } catch (clipboardErr) {
      const textarea = document.createElement('textarea');
      textarea.value = shareUrl;
      document.body.appendChild(textarea);
      textarea.select();
      try {
        document.execCommand('copy');
        toast({
          description: tp.shareSuccess,
          duration: 2000,
        });
      } catch (fallbackErr) {
        toast({
          variant: "destructive",
          description: tp.shareError,
          duration: 2000,
        });
      } finally {
        document.body.removeChild(textarea);
      }
    }
  };

  const groupedPrompts = filteredPrompts.reduce((acc, prompt) => {
    if (!acc[prompt.title]) {
      acc[prompt.title] = [];
    }
    acc[prompt.title].push(prompt);
    return acc;
  }, {});

  const showVersions = (e, versions) => {
    e.preventDefault();
    setSelectedVersions(versions);
  };

  const handleCreatePrompt = async () => {
    if (!newPrompt.title.trim() || !newPrompt.content.trim()) {
      toast({
        variant: "destructive",
        description: tp.createValidation,
        duration: 2000,
      });
      return;
    }

    if (!validateModelConfig()) return;

    setIsSubmitting(true);
    try {
      // 检查标题+版本号是否重复
      const checkResponse = await fetch(`/api/prompts/check-duplicate?title=${encodeURIComponent(newPrompt.title)}&version=${encodeURIComponent(newPrompt.version)}`);
      if (checkResponse.ok) {
        const checkData = await checkResponse.json();
        if (checkData.exists) {
          toast({
            variant: "destructive",
            description: checkData.message,
            duration: 3000,
          });
          setIsSubmitting(false);
          return;
        }
      }
      const payload = {
        prompt: { ...newPrompt },
        model: {
          ...modelConfig,
          temperature: Number(modelConfig.temperature),
          max_tokens: Number(modelConfig.max_tokens),
          top_p: Number(modelConfig.top_p),
          presence_penalty: Number(modelConfig.presence_penalty),
          frequency_penalty: Number(modelConfig.frequency_penalty),
          n: Number(modelConfig.n),
          stop: modelConfig.stop ? modelConfig.stop.split(',').map(s => s.trim()).filter(Boolean) : null,
          logit_bias: modelConfig.logit_bias ? JSON.parse(modelConfig.logit_bias) : null,
          stream: Boolean(modelConfig.stream)
        }
      };

      const res = await fetch('/api/prompts/createPrompts', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
      });

      if (!res.ok) {
        throw new Error('Failed to create prompt');
      }

      const data = await getPrompts();
      setPrompts(data.map(prompt => ({
        ...prompt,
        version: prompt.version || '1.0',
        cover_img: prompt.cover_img || '/default-cover.jpg',
        tags: prompt.tags?.split(',') || []
      })));

      setShowNewPromptDialog(false);
      setNewPrompt({
        title: '',
        content: '',
        description: '',
        tags: 'Chatbot',
        version: '1.0.0',
        cover_img: '',
      });
      setModelConfig({
        channel: '', channel_id: null, model: '', temperature: 1.0, max_tokens: 2048, top_p: 1.0,
        presence_penalty: 0.0, frequency_penalty: 0.0, n: 1, stop: '', logit_bias: '',
        stream: true, api_key: ''
      });
      setModels([]);

      toast({
        description: tp.createSuccess,
        duration: 2000,
      });
    } catch (error) {
      console.error('Error creating prompt:', error);
      toast({
        variant: "destructive",
        description: tp.createError,
        duration: 2000,
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleCreateTag = async (inputValue) => {
    try {
      const response = await fetch('/api/tags', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ name: inputValue }),
      });
      
      if (response.ok) {
        const newOption = { value: inputValue, label: inputValue };
        setTagOptions(prev => [...prev, newOption]);
        return newOption;
      }
    } catch (error) {
      console.error('Error creating new tag:', error);
    }
    return null;
  };

  const handleOptimize = async () => {
    if (!newPrompt.content.trim()) return;
    setIsOptimizing(true);
    setOptimizedContent('');
    setShowOptimizeModal(true);
    
    try {
      const response = await fetch('/api/generate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ text: newPrompt.content }),
      });
      
      if (!response.ok) throw new Error(tp.optimizeError);
      
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let tempContent = '';

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        const chunk = decoder.decode(value);
        const lines = chunk.split('\n').filter(line => line.trim());
        
        for (const line of lines) {
          try {
            const jsonStr = line.replace(/^data: /, '').trim();
            if (!jsonStr || jsonStr === '[DONE]') continue;
            
            const data = JSON.parse(jsonStr);
            if (data.choices?.[0]?.delta?.content) {
              tempContent += data.choices[0].delta.content;
              setOptimizedContent(tempContent);
            }
          } catch (e) {
            console.error(tp.optimizeParsingError, e);
          }
        }
      }

    } catch (error) {
      console.error('Optimization error:', error);
      toast({
        variant: "destructive",
        description: tp.optimizeRetry,
        duration: 2000,
      });
    } finally {
      setIsOptimizing(false);
    }
  };

  return (
    <div className="min-h-[80vh] bg-gradient-to-b from-background to-background/80">
      <div className="container px-4 py-8 sm:py-16 mx-auto max-w-7xl">
        <div className="space-y-8">
          <div className="flex flex-col space-y-6">
            <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4">
              <h1 className="text-3xl font-bold tracking-tight">{tp.title}</h1>
              <div className="flex items-center gap-2 px-4 py-2 bg-secondary/30 rounded-lg">
                <span className="text-sm font-medium text-secondary-foreground">
                  {tp.totalPrompts.replace('{count}', prompts.length.toString())}
                </span>
              </div>
            </div>
            
            <div className="flex flex-col md:flex-row gap-4 items-center">
              <div className="relative w-full md:w-[320px]">
                <div className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground">
                  <Search className="h-4 w-4" />
                </div>
                <Input
                  type="search"
                  onChange={(e) => debouncedSearch(e.target.value)}
                  placeholder={tp.searchPlaceholder}
                  className="w-full h-10 pl-9 pr-4 transition-all duration-200 ease-in-out border rounded-lg focus-visible:ring-2 focus-visible:ring-primary/30 focus-visible:border-primary"
                />
              </div>
              {!isLoading && (
                <>
                  <TagFilter 
                    allTags={allTags}
                    selectedTags={selectedTags}
                    onTagSelect={setSelectedTags}
                    className="touch-manipulation w-full md:w-auto"
                    t={t}
                  />
                  <Link href="/tags" className="w-full md:w-auto">
                    <Button variant="outline" className="w-full group">
                      <Tags className="mr-2 h-4 w-4 group-hover:text-primary transition-colors" />
                      <span className="group-hover:text-primary transition-colors">{tp.manageTags}</span>
                    </Button>
                  </Link>
                </>
              )}
            </div>
          </div>

          {isLoading ? (
            <div className="mt-8">
              <PromptListSkeleton />
            </div>
          ) : (
            <div className="mt-8 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
              <NewPromptCard onClick={() => setShowNewPromptDialog(true)} />
              {Object.entries(groupedPrompts).map(([title, versions]) => {
                const latestPrompt = versions[0];
                return (
                  <Card 
                    key={title}
                    className="group relative rounded-lg border p-5 hover:shadow-lg transition-all duration-300 ease-in-out bg-card cursor-pointer overflow-hidden"
                    onClick={(e) => {
                      e.preventDefault();
                      if (versions.length > 1) {
                        showVersions(e, versions);
                      } else {
                        window.location.href = `/prompts/${latestPrompt.id}`;
                      }
                    }}
                  >
                    <div className="absolute inset-0 bg-gradient-to-br from-primary/5 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
                    
                    <div className="space-y-4 relative z-10">
                      <div className="flex justify-between items-start">
                        <div>
                          <h3 className="text-lg font-semibold line-clamp-1 mb-2 group-hover:text-primary transition-colors">
                            {title}
                          </h3>
                          {latestPrompt.description && (
                            <p className="text-sm text-muted-foreground line-clamp-2">
                              {latestPrompt.description}
                            </p>
                          )}
                        </div>

                        <div className="opacity-0 group-hover:opacity-100 transition-all duration-200 bg-background/90 backdrop-blur-sm rounded-lg p-1 shadow-sm">
                          <div className="flex items-center gap-1">
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={(e) => {
                                e.stopPropagation();
                                handleCopy(latestPrompt.content);
                              }}
                              className="h-8 w-8 hover:bg-accent hover:text-primary"
                            >
                              <Copy className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={(e) => {
                                e.stopPropagation();
                                handleShare(latestPrompt.id);
                              }}
                              className="h-8 w-8 hover:bg-accent hover:text-primary"
                            >
                              <Share2 className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={(e) => {
                                e.stopPropagation();
                                handleDelete(latestPrompt.id);
                              }}
                              className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10"
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </div>
                        </div>
                      </div>

                      <div className="flex flex-wrap gap-2">
                        {latestPrompt.tags.map((tag) => (
                          <span 
                            key={tag}
                            className="bg-secondary/50 text-secondary-foreground text-xs px-2.5 py-0.5 rounded-full font-medium"
                          >
                            #{tag}
                          </span>
                        ))}
                      </div>

                      <div className="flex items-center gap-2 text-xs text-muted-foreground pt-1">
                        <div className="flex items-center gap-1">
                          <Clock className="h-3 w-3" />
                          {new Date(latestPrompt.updated_at).toLocaleString()}
                        </div>
                        {versions.length > 1 && (
                          <div className="flex items-center gap-1 ml-2 bg-primary/10 text-primary px-2 py-0.5 rounded-full">
                            <span>{tp.versionsCount.replace('{count}', versions.length.toString())}</span>
                          </div>
                        )}
                      </div>
                    </div>
                  </Card>
                );
              })}
            </div>
          )}
        </div>
      </div>

      <Dialog open={!!selectedVersions} onOpenChange={() => setSelectedVersions(null)}>
        <DialogContent className="sm:max-w-md">
          <VisuallyHidden.Root><DialogTitle>Dialog</DialogTitle></VisuallyHidden.Root>
          <DialogHeader>
            <DialogTitle className="text-xl">{tp.versionHistoryTitle}</DialogTitle>
          </DialogHeader>
          <div className="space-y-3 mt-4 max-h-[60vh] overflow-y-auto pr-1">
            {selectedVersions?.map((version) => (
              <Link 
                key={version.id} 
                href={`/prompts/${version.id}`}
                className="block"
              >
                <Card className="p-4 hover:bg-accent/50 cursor-pointer transition-colors border border-border/50 hover:border-primary/30">
                  <div className="flex justify-between items-center">
                    <div>
                      <div className="font-medium text-primary">v{version.version}</div>
                      <div className="text-sm text-muted-foreground">
                        {new Date(version.created_at).toLocaleString()}
                      </div>
                    </div>
                    <ChevronDown className="h-4 w-4 text-muted-foreground" />
                  </div>
                </Card>
              </Link>
            ))}
          </div>
        </DialogContent>
      </Dialog>

      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <VisuallyHidden.Root><DialogTitle>Dialog</DialogTitle></VisuallyHidden.Root>
          <DialogHeader>
            <DialogTitle className="text-xl text-destructive">{tp.deleteConfirmTitle}</DialogTitle>
            <DialogDescription>
              {tp.deleteConfirmDescription}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="mt-4 gap-2">
            <Button
              variant="outline"
              onClick={() => setDeleteDialogOpen(false)}
            >
              {tp.cancel}
            </Button>
            <Button
              variant="destructive"
              onClick={confirmDelete}
            >
              {tp.delete}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showNewPromptDialog} onOpenChange={setShowNewPromptDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto scrollbar-thumb-muted/50 scrollbar-track-background">
          <VisuallyHidden.Root><DialogTitle>Dialog</DialogTitle></VisuallyHidden.Root>
          <DialogHeader>
            <DialogTitle className="text-xl">{tp.newPromptTitle}</DialogTitle>
          </DialogHeader>
          <div className="space-y-6 py-4">
            <div className="space-y-2">
              <Label htmlFor="title" className="text-sm font-medium">
                {tp.formTitleLabel}
                <span className="text-red-500 ml-1">*</span>
              </Label>
              <Input
                id="title"
                value={newPrompt.title}
                onChange={(e) => setNewPrompt({ ...newPrompt, title: e.target.value })}
                placeholder={tp.formTitlePlaceholder}
                className="focus-visible:ring-primary/30"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="content" className="text-sm font-medium">
                {tp.formContentLabel}
                <span className="text-red-500 ml-1">*</span>
              </Label>
              <div className="relative">
                <Textarea
                  id="content"
                  value={newPrompt.content}
                  onChange={(e) => setNewPrompt({ ...newPrompt, content: e.target.value })}
                  placeholder={tp.formContentPlaceholder}
                  className="min-h-[200px] pr-10 focus-visible:ring-primary/30"
                />
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="absolute right-2 top-2 hover:bg-accent hover:text-primary"
                  onClick={handleOptimize}
                  disabled={!newPrompt.content.trim() || isOptimizing}
                >
                  {isOptimizing ? (
                    <Loader2 className="h-4 w-4 animate-spin" />
                  ) : (
                    <Wand2 className="h-4 w-4" />
                  )}
                </Button>
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="description" className="text-sm font-medium">{tp.formDescriptionLabel}</Label>
              <Textarea
                id="description"
                value={newPrompt.description}
                onChange={(e) => setNewPrompt({ ...newPrompt, description: e.target.value })}
                placeholder={tp.formDescriptionPlaceholder}
                className="focus-visible:ring-primary/30"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="tags" className="text-sm font-medium">{tp.formTagsLabel}</Label>
              <CreatableSelect
                isMulti
                value={newPrompt.tags ? newPrompt.tags.split(',').map(tag => ({ value: tag, label: tag })) : []}
                onChange={(selected) => {
                  const tags = selected ? selected.map(option => option.value).join(',') : '';
                  setNewPrompt({ ...newPrompt, tags });
                }}
                options={tagOptions}
                onCreateOption={async (inputValue) => {
                  const newOption = await handleCreateTag(inputValue);
                  if (newOption) {
                    const newTags = newPrompt.tags 
                      ? `${newPrompt.tags},${inputValue}` 
                      : inputValue;
                    setNewPrompt({ ...newPrompt, tags: newTags });
                  }
                }}
                placeholder={tp.formTagsPlaceholder}
                classNamePrefix="select"
                styles={{
                  control: (baseStyles, state) => ({
                    ...baseStyles,
                    backgroundColor: 'hsl(var(--background))',
                    borderColor: state.isFocused ? 'hsl(var(--primary))' : 'hsl(var(--border))',
                    borderRadius: 'calc(var(--radius) - 2px)',
                    boxShadow: state.isFocused ? '0 0 0 2px hsl(var(--primary)/30%)' : 'none',
                    '&:hover': {
                      borderColor: 'hsl(var(--primary))',
                    },
                  }),
                  menu: (baseStyles) => ({
                    ...baseStyles,
                    backgroundColor: 'hsl(var(--background))',
                    border: '1px solid hsl(var(--border))',
                    borderRadius: 'calc(var(--radius) - 2px)',
                    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)',
                    zIndex: 100,
                  }),
                  option: (baseStyles, { isFocused, isSelected }) => ({
                    ...baseStyles,
                    backgroundColor: isSelected 
                      ? 'hsl(var(--primary))' 
                      : isFocused 
                        ? 'hsl(var(--accent))' 
                        : 'transparent',
                    color: isSelected 
                      ? 'hsl(var(--primary-foreground))' 
                      : 'inherit',
                    cursor: 'pointer',
                    '&:active': {
                      backgroundColor: 'hsl(var(--accent))',
                    },
                  }),
                  multiValue: (baseStyles) => ({
                    ...baseStyles,
                    backgroundColor: 'hsl(var(--secondary)/50%)',
                    borderRadius: 'calc(var(--radius) - 2px)',
                  }),
                  multiValueLabel: (baseStyles) => ({
                    ...baseStyles,
                    color: 'hsl(var(--secondary-foreground))',
                  }),
                  multiValueRemove: (baseStyles) => ({
                    ...baseStyles,
                    color: 'hsl(var(--secondary-foreground))',
                    '&:hover': {
                      backgroundColor: 'hsl(var(--destructive))',
                      color: 'hsl(var(--destructive-foreground))',
                    },
                  }),
                  input: (baseStyles) => ({
                    ...baseStyles,
                    color: 'hsl(var(--foreground))',
                  }),
                }}
                theme={(theme) => ({
                  ...theme,
                  colors: {
                    ...theme.colors,
                    primary: 'hsl(var(--primary))',
                    primary75: 'hsl(var(--primary)/.75)',
                    primary50: 'hsl(var(--primary)/.5)',
                    primary25: 'hsl(var(--primary)/.25)',
                    danger: 'hsl(var(--destructive))',
                    dangerLight: 'hsl(var(--destructive)/.25)',
                  },
                })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="version" className="text-sm font-medium">{tp.formVersionLabel}</Label>
              <div className="flex items-center gap-2">
                <span className="text-sm text-muted-foreground">v</span>
                <Input
                  id="version"
                  value={newPrompt.version}
                  onChange={(e) => setNewPrompt({ ...newPrompt, version: e.target.value })}
                  placeholder={tp.formVersionPlaceholder}
                  className="w-32 focus-visible:ring-primary/30"
                />
              </div>
              <p className="text-sm text-muted-foreground">
                {tp.versionSuggestion}
              </p>
            </div>

            <div className="space-y-2">
              <div className="flex items-center justify-between cursor-pointer select-none" onClick={() => setShowModelConfig(!showModelConfig)}>
                <Label className="text-sm font-medium">模型配置<span className="text-red-500 ml-1">*</span></Label>
                <span className="text-xs text-muted-foreground">{showModelConfig ? '折叠' : '展开'}</span>
              </div>
              {showModelConfig && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 border rounded-md p-4">
                  <div>
                    <Label>
                      渠道名称
                      <span className="text-red-500 ml-1">*</span>
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>渠道名称</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <select
                      className="block w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                      value={modelConfig.channel}
                      onChange={e => {
                        const selectedChannel = channels.find(ch => ch.name === e.target.value);
                        setModelConfig({ 
                          ...modelConfig, 
                          channel: e.target.value,
                          channel_id: selectedChannel ? selectedChannel.id : null,
                          model: '' // 清空模型选择
                        });
                      }}
                      required
                    >
                      <option value="">选择渠道</option>
                      {channels.map(channel => (
                        <option key={channel.id} value={channel.name}>
                          {channel.name}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <Label>
                      模型名称
                      <span className="text-red-500 ml-1">*</span>
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>选择渠道后获取可用模型列表</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <select
                      className={`block w-full rounded-md border border-input bg-background px-3 py-2 text-sm ${!modelConfig.channel_id ? 'opacity-50 cursor-not-allowed' : ''}`}
                      value={modelConfig.model}
                      onChange={e => setModelConfig({ ...modelConfig, model: e.target.value })}
                      disabled={!modelConfig.channel_id}
                      required
                    >
                      <option value="">{modelConfig.channel_id ? '选择模型' : '请先选择渠道'}</option>
                      {models.map(model => (
                        <option key={model.model} value={model.model}>
                          {model.model}
                        </option>
                      ))}
                    </select>
                  </div>

                  <div>
                    <Label>
                      temperature
                      <span className="text-red-500 ml-1">*</span>
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>控制输出随机性：值越高越随机，值越低越确定，取值范围 [0, 2]</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <Input required type="number" step="0.1" min={0} max={2} value={modelConfig.temperature} onChange={e => setModelConfig({ ...modelConfig, temperature: e.target.value })} />
                  </div>
                  <div>
                    <Label>
                      max_tokens
                      <span className="text-red-500 ml-1">*</span>
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>生成内容的最大 token 数量（[10, 30000]，默认 2048）</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <Input required type="number" min={10} max={30000} value={modelConfig.max_tokens} onChange={e => setModelConfig({ ...modelConfig, max_tokens: e.target.value })} />
                  </div>
                  <div>
                    <Label>
                      top_p
                      <span className="text-red-500 ml-1">*</span>
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>核采样，仅考虑累积概率达到阈值的 token，取值范围 [0, 2]</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <Input required type="number" step="0.1" min={0} max={2} value={modelConfig.top_p} onChange={e => setModelConfig({ ...modelConfig, top_p: e.target.value })} />
                  </div>
                  <div>
                    <Label>
                      presence_penalty
                      <span className="text-red-500 ml-1">*</span>
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>鼓励新话题：正值增加新主题概率，负值减少，取值范围 [-2, 2]</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <Input required type="number" step="0.1" min={-2} max={2} value={modelConfig.presence_penalty} onChange={e => setModelConfig({ ...modelConfig, presence_penalty: e.target.value })} />
                  </div>
                  <div>
                    <Label>
                      frequency_penalty
                      <span className="text-red-500 ml-1">*</span>
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>惩罚重复：正值降低重复内容概率，负值减少，取值范围 [-2, 2]</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <Input required type="number" step="0.1" min={-2} max={2} value={modelConfig.frequency_penalty} onChange={e => setModelConfig({ ...modelConfig, frequency_penalty: e.target.value })} />
                  </div>
                  <div>
                    <Label>
                      n
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>生成多个独立回复（如 n=3 返回 3 个选项）</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <Input type="number" value={modelConfig.n} onChange={e => setModelConfig({ ...modelConfig, n: e.target.value })} />
                  </div>
                  <div>
                    <Label>
                      stop (逗号分隔)
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>设置停止词，遇到即终止生成（如 ["\n", "。"]）</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <Input value={modelConfig.stop} onChange={e => setModelConfig({ ...modelConfig, stop: e.target.value })} />
                  </div>
                  <div>
                    <Label>
                      logit_bias (JSON)
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>{'调整特定 token 的生成概率（如 {"1234": 2.0}）'}</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <Input value={modelConfig.logit_bias} onChange={e => setModelConfig({ ...modelConfig, logit_bias: e.target.value })} placeholder='{"123": -5}' />
                  </div>
                  <div>
                    <Label>
                      stream
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>启用流式传输，逐块返回结果</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <select
                      className="block w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                      value={modelConfig.stream ? 'true' : 'false'}
                      onChange={e => setModelConfig({ ...modelConfig, stream: e.target.value === 'true' })}
                    >
                      <option value="false">false</option>
                      <option value="true">true</option>
                    </select>
                  </div>
                  <div>
                    <Label>api_key</Label>
                    <Input value={modelConfig.api_key} onChange={e => setModelConfig({ ...modelConfig, api_key: e.target.value })} />
                  </div>
                </div>
              )}
            </div>
          </div>
          <DialogFooter className="gap-2">
            <Button
              variant="outline"
              onClick={() => setShowNewPromptDialog(false)}
            >
              {tp.cancel}
            </Button>
            <Button
              onClick={handleCreatePrompt}
              disabled={isSubmitting}
              className="gap-2"
            >
              {isSubmitting ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin" />
                  {tp.creating}
                </>
              ) : (
                <>
                  <PlusCircle className="h-4 w-4" />
                  {tp.create}
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showOptimizeModal} onOpenChange={setShowOptimizeModal}>
        <DialogContent className="max-w-3xl max-h-[90vh]">
          <VisuallyHidden.Root><DialogTitle>Dialog</DialogTitle></VisuallyHidden.Root>
          <DialogHeader>
            <DialogTitle className="text-xl flex items-center gap-2">
              <Wand2 className="h-5 w-5 text-primary" />
              {tp.optimizePreviewTitle}
            </DialogTitle>
          </DialogHeader>
          <div className="relative min-h-[200px] max-h-[50vh] overflow-y-auto mt-4 border rounded-lg p-1">
            {isOptimizing && (
              <div className="absolute inset-0 flex items-center justify-center bg-background/80 backdrop-blur-sm z-10">
                <div className="flex flex-col items-center gap-3">
                  <Loader2 className="h-8 w-8 animate-spin text-primary" />
                  <p className="text-sm text-muted-foreground">{tp.optimizePlaceholder}</p>
                </div>
              </div>
            )}
            <Textarea
              value={optimizedContent}
              onChange={(e) => setOptimizedContent(e.target.value)}
              className="min-h-[200px] w-full border-0 focus-visible:ring-0 resize-none"
              placeholder={isOptimizing ? '' : tp.optimizePlaceholder}
            />
          </div>
          <DialogFooter className="gap-2 mt-4">
            <Button
              variant="outline"
              onClick={() => setShowOptimizeModal(false)}
            >
              {tp.cancel}
            </Button>
            <Button
              onClick={() => {
                setNewPrompt({ ...newPrompt, content: optimizedContent });
                setShowOptimizeModal(false);
              }}
              disabled={!optimizedContent.trim()}
              className="gap-2"
            >
              <Wand2 className="h-4 w-4" />
              {tp.applyOptimization}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}